import threading
import time
import select
import socket
import packet
import sys

# code running in a different thread - the select thread
class Server_select_thread( threading.Thread ):
	def __init__(self, parent, verbose):
		threading.Thread.__init__(self)
		self.parent	= parent
		self.verbose= verbose
	
	def run(self):
		while self.parent.bool_running:
			# if slide number has changed - send slide number to all
			if self.parent.int_current_slide != self.parent.int_sent_slide:
				self.parent.int_sent_slide = self.parent.int_current_slide
				str_prespack = packet.encode_server_packet('psno', self.parent.int_current_slide)
				if self.verbose: print "Slide number sent"
				for sock in self.parent.list_input_sock:
					if ((sock is not sys.stdin) and (sock is not self.parent.sock_server)):
						if ( str_prespack != None ):
							sock.send(str_prespack)

			# process incoming packets
			inputready,outputready,exceptready = select.select(self.parent.list_input_sock,[],[],.5)
		
			for s in inputready:
				if s == self.parent.sock_server:
					# incomning connection
					client, address = self.parent.sock_server.accept()
					if self.verbose: print "Incoming client connection accepted..."
					self.parent.list_input_sock.append(client)
				else:
					# incoming data from existing connection
					var_packet = packet.receive_packet(s, True)
					if var_packet is not None:
						var_result = packet.decode_server_packet(var_packet)
						if var_result is not None:
							self.parent.parse_packet(var_result, s);
		
		if self.verbose: print "CLEANUP",
		# cleanup sockets
		str_prespack = packet.encode_server_packet('ares', (False, "The presentation is over."))
		for sock in self.parent.list_input_sock[:]:
			if sock is not self.parent.sock_server:
				# 	we need to "gently" notify the users the presentation is over
				if ( str_prespack != None ):
					sock.send(str_prespack)
					if self.verbose: print "Sent presentation over messge to:",self.parent.client_list.get_name(sock)
				self.parent.list_input_sock.remove(sock)
				sock.close()
				
		self.parent.sock_server.close()
		
		# cleanup images
		self.parent.cleanup_images()

